package com.perfma.xtest.agent;


import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;


public class VmProvider {

    private static final String DEFAULT = "default";

    private static final String JVM_SUPPORT = "Jvm-Support";

    public static List<URL> getURL(String jdkPath, Double nowVmVersion) throws IOException {
        File jdkFileDir = new File(jdkPath);
        List<URL> urls = new ArrayList<URL>();
        if (jdkFileDir.exists()) {
            File[] files = jdkFileDir.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    if (name.startsWith("agent") && name.endsWith("jar")) {
                        return true;
                    }
                    return false;
                }
            });
            if (files == null || files.length == 0) {
                System.err.println("jdk provider url is not exist");
                return null;
            }
            Double supportVmVersion = null;
            File supportFileJar = null;
            File defaultFileJar = null;
            for (File vmFileJar : files) {
                Attributes attributes = read(vmFileJar);
                String version = attributes.getValue(JVM_SUPPORT);
                if (version.equals(DEFAULT)) {
                    defaultFileJar = vmFileJar;
                    continue;
                }
                double vmJarVersion = Double.parseDouble(version);
                if (supportVmVersion == null && vmJarVersion <= nowVmVersion) {
                    supportVmVersion = vmJarVersion;
                    supportFileJar = vmFileJar;
                } else {
                    if (vmJarVersion <= nowVmVersion && vmJarVersion > supportVmVersion) {
                        supportVmVersion = vmJarVersion;
                        supportFileJar = vmFileJar;
                    }
                }
            }
            if (supportFileJar == null) {
                supportFileJar = defaultFileJar;
            }
            urls.add(supportFileJar.toURI().toURL());
        }
        return urls;
    }

    public static Attributes read(File jarFile) throws IOException {
        JarFile jar = null;
        Attributes attributes = null;
        try {
            jar = new JarFile(jarFile);
            Manifest manifest = jar.getManifest();
            attributes = manifest.getMainAttributes();
        } finally {
            if (jar != null) {
                try {
                    jar.close();
                } catch (final IOException ioe) {
                    ioe.printStackTrace(System.err);
                }
            }
        }
        return attributes;
    }
}
